package com.example.piece.ui.dialog

import com.example.base.aop.click.RepeatClick
import com.example.base.ext.toast
import com.example.base.tools.ConfigTool
import com.example.base.ui.dialog.UIDialog
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.databinding.DialogDebugServerBinding
import com.example.piece.net.NetManager
import java.util.regex.Pattern

/**  调试服务器地址弹窗  **/
class DebugServerDialog : UIDialog<DialogDebugServerBinding>() {

    override fun getContentRes(): Int = R.layout.dialog_debug_server

    override fun initData() {
        val customServerLocation = ConfigTool.getString(Key.DataKey.SERVER_LOCATION)
        mBinding.etServerIp.setText(
            if (customServerLocation.isEmpty())
                NetManager.BASE_SERVER_URL_TEST
            else customServerLocation
        )
        mBinding.btnConfirm.setOnClickListener {
            setServerIP()
        }
    }

    /**  ip 地址校验的正则  **/
    private val ipPattern =
        "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}"
    private val rule by lazy {
        Pattern.compile(ipPattern)
    }

    /**  设置服务器地址  **/
    @RepeatClick
    private fun setServerIP() {
        ConfigTool.putString(Key.DataKey.SERVER_LOCATION, mBinding.etServerIp.text.toString())
        toast("设置成功!")
        dismiss()
    }

}